package com.demo.meidianapp.mvp.base.retroft;


import android.util.Log;

import java.util.concurrent.TimeUnit;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/*
 * 描述:     TODO
 */
public class BaseApiImpl implements BaseApi {
    protected Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
    private OkHttpClient.Builder mOkHttpClient;
    private Retrofit mRetrofit;

    public BaseApiImpl(final String baseUrl) {
        this.mOkHttpClient = RetrofitUrlManager.getInstance().with(new OkHttpClient.Builder())
                .readTimeout(5, TimeUnit.SECONDS).connectTimeout(5, TimeUnit.SECONDS)
                .addInterceptor(getLoggerInterceptor()).build().newBuilder();

        this.mRetrofit = new Retrofit.Builder().baseUrl(baseUrl).addCallAdapterFactory
                (RxJava2CallAdapterFactory.create())//使用rxjava
                .addConverterFactory(GsonConverterFactory.create())//使用Gson
                .client(mOkHttpClient.build()).build();

    }

    /**
     * 构建retroft
     *
     * @return Retrofit对象
     */
    @Override
    public Retrofit getRetrofit() {
        if (mRetrofit == null) {
            //锁定代码块
            synchronized (BaseApiImpl.class) {
                if (mRetrofit == null) {
                    mRetrofit = retrofitBuilder.build(); //创建retrofit对象
                }
            }
        }
        return mRetrofit;

    }


    @Override
    public OkHttpClient.Builder setInterceptor(Interceptor interceptor) {
        return mOkHttpClient.addInterceptor(interceptor);
    }

    @Override
    public Retrofit.Builder setConverterFactory(Converter.Factory factory) {
        return retrofitBuilder.addConverterFactory(factory);
    }

    /**
     * 日志拦截器
     * 将你访问的接口信息
     *
     * @return 拦截器
     */
    public HttpLoggingInterceptor getLoggerInterceptor() {
        //日志显示级别
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.HEADERS;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                    Log.d("ApiUrl", "--->" + message);
            }
        });
        loggingInterceptor.setLevel(level);
        return loggingInterceptor;
    }
}
